package com.colin.client;


import com.colin.client.userbean.ResponseUserToken;
import com.colin.client.userbean.ResultCode;
import com.colin.client.userbean.ResultJson;
import com.google.gson.Gson;
import io.itit.itf.okhttp.FastHttpClient;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;


/**
 * 登录地址：https://exp.nationauth.cn/idaas/user/login
 */
@RestController
public class HellowController {


    /**
     * basic的服务
     */
    private static final String BASIC_URI = "http://127.0.0.1:7001/basic/apis/v1/auth/code";


    private static final String REDIRECT_URI = "http://127.0.0.1:8001/clinet/index";


    private static final String BASE_OAUTH_URI = "https://exp.nationauth.cn/";


    private static final String AUTHORIZATION_URI = BASE_OAUTH_URI+"idaas-boot/oauth/authorize";
    private static final String TOKEN_URI = BASE_OAUTH_URI+"idaas-boot/oauth/access_token";
    private static final String USERINFO_URI = BASE_OAUTH_URI+"idaas-boot/oauth/user";

    private static final String CLIENT_ID = "cUJdUSzGYJhUDvHThVlTrbOYflOjUSma";
    private static final String CLIENT_SECRET = "woGoYdeZhnmKHIXezFTyNxNwEfKeRvtT";
    private static final String GRANT_TYPE = "authorization_code";


    /**
     * 根据code 获取对应的tokenbean
     * @param code
     * @return
     */
    private static TokenBean getTokenBeanByCode(String code) throws Exception {
        Map<String, String> paramMap1 = new HashMap<String, String>();
        paramMap1.put("code", code);
        paramMap1.put("client_id", CLIENT_ID);
        paramMap1.put("client_secret", CLIENT_SECRET);

        paramMap1.put("redirect_uri", REDIRECT_URI);
        paramMap1.put("grant_type", GRANT_TYPE);

        String resp = FastHttpClient.post().url(TOKEN_URI).addParams(paramMap1).build().execute().string();

        Gson gson = new Gson();
        TokenBean tokenBean = gson.fromJson(resp, TokenBean.class);

        System.out.println(tokenBean.toString());

        return tokenBean;
    }

    // url:https://exp.nationauth.cn/idaas-boot/oauth/user 参数：header中 添加Authorization Bearer xxxtokenxxxx
    private static String getUserCodeByToken(String access_token) throws Exception {
        String token = "Bearer "+access_token; //将token放入到header中
        String resp = FastHttpClient.get().url(USERINFO_URI).addHeader("Authorization",token).build().execute().string();

        Gson gson = new Gson();
        AuthUserBean authUserBean = gson.fromJson(resp, AuthUserBean.class);

        if(null != authUserBean){
            return authUserBean.getName();//获取userCode
        }

        return "";
    }

    private static ResultJson<ResponseUserToken> getUserInfoByCode(String userCode) throws Exception {

      //  System.out.println("BASIC_URI"+BASIC_URI+"?code="+userCode);
        String resp = FastHttpClient.post().url(BASIC_URI).addParams("code",userCode).build().execute().string();

        Gson gson = new Gson();
        ResultJson<ResponseUserToken> responseUserToken = gson.fromJson(resp, ResultJson.class);


        System.out.println("结果状态码："+responseUserToken.getCode());

        return responseUserToken;

//        int rscode = responseUserToken.getCode();
//
//        if(null != responseUserToken && 200 == rscode){
//            return responseUserToken;
//        }else{
//
//        }

    }

    /**
     * 受限制访问，用户权限不限
     */
    @RequestMapping("client/index")
    public ModelAndView client(HttpServletResponse response, HttpServletRequest request) throws Exception {

        String code = request.getParameter("code");

        if(StringUtils.isEmpty(code)){
            String url = AUTHORIZATION_URI+"?scope=openid profile email phone&response_type=code&client_id=cUJdUSzGYJhUDvHThVlTrbOYflOjUSma&redirect_uri=http://127.0.0.1:8001/client/index";
            System.out.println("url:"+url);
            response.sendRedirect(url);
            return null;
        }else{
            // 根据code 发送post 请求
            TokenBean tokenBean = getTokenBeanByCode(code);

            String access_token = tokenBean.getAccess_token();

           String userCode =  getUserCodeByToken(access_token);




            System.out.println("userCode:"+userCode);

            if(null == userCode || userCode.isEmpty()){
                System.out.println("子basic系统未找到对应的userCode");
            }


            ResultJson<ResponseUserToken> rut =  getUserInfoByCode(userCode);


            if(null != rut){
                System.out.println("结果数据："+rut.toString());
            }


             ModelAndView mv= new ModelAndView("client/index");
             mv.addObject("code", rut.toString());
             return mv;
        }




        //第一步 获取code
       // GET请求 获取重定向的值 https://exp.nationauth.cn/idaas-boot/oauth/authorize?scope=openid profile email phone&response_type=code&client_id=cUJdUSzGYJhUDvHThVlTrbOYflOjUSma&redirect_uri=http://127.0.0.1:8001/client/index


        //第二步 根据code 获取token返回：
        /**
         *
         * POST请求 获取访问的token：https://exp.nationauth.cn/idaas-boot/oauth/access_token
         * code:XszvhQeeaOGnWerVhnmltHmwLFcouYGZ
         * client_id:cUJdUSzGYJhUDvHThVlTrbOYflOjUSma
         * client_secret:woGoYdeZhnmKHIXezFTyNxNwEfKeRvtT
         * redirect_uri:http://127.0.0.1:8001/clinet/index
         * grant_type:authorization_code
         */

        /**
         * return
         * {
         * 	"access_token": "11.56dc7b0406be943e537b2264396a9687a20e5ab6.2592000.1659757131",
         * 	"id_token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ3cXEiLCJhdWQiOiJjVUpkVVN6R1lKaFVEdkhUaFZsVHJiT1lmbE9qVVNtYSIsImlzcyI6Imh0dHBzOi8vZXhwLm5hdGlvbmF1dGguY24vaWRhYXMtYm9vdC9vYXV0aC9hdXRob3JpemUiLCJleHAiOjE2NTcxNjY5OTEsImlhdCI6MTY1NzE2NTEzMX0.0NCaLaNCL_hbVh3-36XV2zkhhE0UWiQynR_H1I9_Tgo",
         * 	"refresh_token": "12.012f72b9664f3da34942f5e86309898fa48d071a.31536000.1688701131",
         * 	"token_type": "Bearer",
         * 	"expires_in": 2592000,
         * 	"scope": "openid profile email phone"
         * }
         */

        //第三步 根据token获取用户名  url:https://exp.nationauth.cn/idaas-boot/oauth/user 参数：header中 添加Authorization Bearer xxxtokenxxxx
        /**
         * return {
         * 	"name": "wqq",
         * 	"sub": "wqq",
         * 	"email": null
         * }
         */

        //第四步，根据用户名查询用户的数据 将用户的数据返回到client/index中 在index中将token之类的返回到系统中。

       // ModelAndView mv= new ModelAndView("client/index");
       // return mv;
    }

}
